package practise.mulitThreads.ConcurrentInPractice.BoundedBuffer;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by richard on 6/14/14.
 */
public class TestForBoundedBuffer {
    public static void main(String[] args) {
        BoundedBuffer<Integer> container = new BoundedBuffer<>();
        AtomicInteger number = new AtomicInteger(0);
        Runnable getThread = new Runnable() {
            @Override
            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println("get " + container.poll());

                        Thread.sleep(1000);

                    }

                } catch (InterruptedException e) {
//                    Thread.currentThread().interrupt();todo cannot use this, in this method it just modify one thread state
                }
                System.out.println("getThreadInterrupted");
            }
        };

        Runnable putThread = new Runnable() {

            @Override
            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println("put number " + number.incrementAndGet());
                        container.offer(number.get());

                        Thread.sleep(500);

                    }
                } catch (InterruptedException e) {
//                    Thread.currentThread().interrupt(); todo cannot use this, in this method it just modify one thread state
                }
                System.out.println("putThreadInterrupted");
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(getThread);
        executorService.execute(putThread);

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        executorService.shutdownNow();
    }
}
